<template>
  <a-card :title="this.$route.query.processName">
    <a-tabs v-model="key" @change="tabChange">
      <a-tab-pane key="1">
        <span slot="tab">
          <a-icon type="unordered-list" />
          字段配置
        </span>

        <!-- 左侧选择字段容器 -->
        <div class="leftBox" ref="tableRef">
          <div class="gundongBox">
            <TaskFormView
              ref="formView"
              @fGetEditData="sGetEditData"
              @fAddItem="sAddItem"
              @fSetActive="sSetActive"
              :pattern="1"
            ></TaskFormView>
          </div>
        </div>

        <!-- 右侧选中字段容器 -->

        <a-card class="rightBox">
          <a-row class="titleRowBox">
            <div style="width: 13%" :span="3">控件</div>
            <div style="width: 20%" :span="4">数据项</div>
            <div style="width: 20%" :span="4">状态</div>
            <div style="width: 20%" :span="4">
              自动赋值
              <a-popover placement="topLeft">
                <template slot="content">
                  <span>系统默认值</span>
                </template>
                <a-button @click="showDefaultValue" type="link" icon="question-circle"></a-button>
              </a-popover>
            </div>
            <div style="width: 15%" :span="4">流程变量</div>
            <a-button v-if="spinning == false" type="primary" size="small" icon="plus" @click="modelShow(true)">
              添加
            </a-button>
            <a-col :span="1"></a-col>
          </a-row>
          <!-- 内容主体 -->
          <a-spin size="large" :spinning="fieldLoading">
            <div v-if="configureList.length > 0 && fieldLoading == false" class="gundongBox">
              <span
                :ref="`select${item.field_}`"
                class="cardBox"
                v-for="(item, index) in configureList"
                :key="item.field_"
              >
                <a-row style="width: 100%; padding-left: 20px">
                  <a-col :span="3">
                    <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>{{ item.label_ }}</span>
                      </template>
                      <span>{{
                        item.label_ && item.label_.length > 5 ? item.label_.substring(0, 5) + '...' : item.label_
                      }}</span>
                    </a-tooltip></a-col
                  >
                  <a-col :span="5">
                    <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>{{ item.field_ }}</span>
                      </template>
                      <span>{{
                        item.field_ && item.field_.length > 15 ? item.field_.substring(0, 15) + '...' : item.field_
                      }}</span>
                    </a-tooltip></a-col
                  >
                  <a-col :span="4">
                    <a-select
                      v-if="EditMap[item.field_] && EditMap[item.field_].options.hidden == false"
                      v-model="item.status_"
                      style="width: 120px"
                      placeholder="请选择"
                    >
                      <!-- 隐藏字段 hidden 为 true -->
                      <a-select-option :value="90600"> 可编辑 </a-select-option>
                      <a-select-option :value="90601"> 隐藏 </a-select-option>
                    </a-select>
                    <span v-else>隐藏</span>
                  </a-col>
                  <a-col style="margin-left: 14px" :span="5"
                    ><a-input
                      v-if="item.field_.indexOf('#') > -1"
                      style="width: 130px"
                      v-model="item.value_"
                      @focus="colForcus(index, item)"
                      @blur="colBlur(index, item)"
                      placeholder="请输入默认值"
                  /></a-col>

                  <a-col style="margin-left: -5px" :span="5">
                    <a-input
                      v-if="item.field_.indexOf('#') > -1"
                      style="width: 130px"
                      v-model="item.variname_"
                      @focus="colForcus(index, item)"
                      @blur="colBlur(index, item)"
                      placeholder="请输入流程变量"
                    />
                  </a-col>
                  <a-col class="closeBox" @click="delCol(index, item)" :span="1"
                    ><div><a-icon type="close" /></div
                  ></a-col>
                </a-row>
              </span>
            </div>
            <!-- 引导图片 -->
            <div v-else>
              <div class="tipBox">
                <img class="imgBox" src="@/assets/images/guide/checkTip.svg" />
              </div>
              <div class="tipTextBox">*双击左侧项或点击添加按钮勾选字段</div>
              <div class="tipTextBox">(未配置的表单项在流程内将以预览方式显示)</div>
            </div>
          </a-spin>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="2">
        <span slot="tab">
          <a-icon type="plus-square" />
          按钮配置
        </span>
        <NodeBtn ref="btnRef" @handleBack="handleBack"></NodeBtn>
      </a-tab-pane>
    </a-tabs>

    <div class="buttonBox">
      <a-button :style="{ marginRight: '15px' }" icon="rollback" @click="handleBack"> 返回 </a-button>
      <a-button
        :loading="loading"
        :style="{ marginRight: '15px' }"
        type="primary"
        icon="save"
        @click="handleSave(false)"
      >
        保存
      </a-button>
      <a-button :loading="loading" type="primary" icon="save" @click="handleSave(true)"> 保存并返回 </a-button>
    </div>

    <!-- 弹出层 -->
    <a-modal width="40%" v-model="isModel" title="选择字段" :footer="null" @cancel="visible = false">
      <div class="gundongBox">
        <div class="spin-content">
          已选择&nbsp;
          <a class="f-w-600" v-text="selectedRowKeys.length"></a>
          项&nbsp;
        </div>
        <a-table
          rowKey="id"
          :scroll="{ y: 400 }"
          :columns="tabcolumns"
          :data-source="udata"
          :pagination="tabpagination"
          @change="tableChange"
          size="middle"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
        </a-table>
        <a-row style="text-align: center">
          <a-button type="primary" :disabled="!selectedRowKeys.length" @click="modelSave"> 确定选择 </a-button>
        </a-row>
      </div>
    </a-modal>

    <!-- 系统默认值弹出框 -->
    <a-modal
      width="40%"
      v-model="defaultvalueModel"
      title="系统默认值"
      :footer="null"
      @cancel="defaultvalueModel = false"
    >
      <div class="modelBox">
        <a-form-item
          v-for="(value, key) in Tp_defaultvalue"
          :key="key"
          :label="value.name"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          {{ value.value }}
        </a-form-item>
      </div>
    </a-modal>
  </a-card>
</template>
<script>
import { findTableFieldList } from '@/api/base/table_meta.js'
import { setpFieldBatchSave, setpFieldList } from '@/api/workflow/act_dsn_form_step.js'
import TaskFormView from '@/views/workflow/Wf_TaskForm.vue'
import NodeBtn from '@/views/workflow/Wf_NodeBtn.vue'
import { Tp_tab } from '@/enumeration/Tp_tab'
import { Tp_defaultvalue } from '@/enumeration/Tp_defaultvalue.js'

export default {
  data() {
    return {
      labelCol: { span: 6 }, // label宽
      wrapperCol: { span: 18 }, // 组件宽
      defaultvalueModel: false, // 默认值弹框状态
      Tp_defaultvalue: Tp_defaultvalue, // 系统默认值枚举
      fieldLoading: true,
      key: '1', // tab切换key
      loading: false, // 按钮保存状态
      udata: [], // 表格渲染对象
      Tp_tab: Tp_tab, // 表类型枚举
      EditMap: {}, // 编辑模式- 子组件渲染数据
      spinning: true, // 加载状态
      isModel: false, // 弹出层状态控制
      fieldMap: {}, // 字段列表转map方法查找 (只有index)
      alreadyList: [], // 已经选择过了的 (只有字段name)
      configureList: [], // 选择的配置列表 (要保存的整个对象)
      fieldList: [], // 字段列表
      queryParam: { pageSize: 2147483647, sort: 'indexsort', order: 'asc' }, // 回显查询条件
      selectedRowKeys: [], // 选中的行id
      tabpagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      tabcolumns: [
        {
          title: '控件',
          dataIndex: 'label',
          width: '1',
          align: 'left',
        },
        {
          title: '数据项',
          align: 'left',
          dataIndex: 'fieldName',
          width: '1',
        },
        {
          title: '描述',
          align: 'left',
          dataIndex: 'fieldDescription',
          width: '1',
        },
      ],
    }
  },
  created() {
    console.log('路由参数', this.$route.params)
  },
  methods: {
    // 显示默认值弹框
    showDefaultValue() {
      this.defaultvalueModel = true
    },
    // tab切换事件
    tabChange(key) {
      console.log('key', key)
    },
    onSelectChange(selectedRowKeys) {
      // 弹出层删除了
      this.selectedRowKeys = selectedRowKeys
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange(pagination) {
      this.tabpagination.current = pagination.current
    },
    findInit(res) {
      if (res.code == 0) {
        // 过滤一下只存表单用到的字段
        res.data.forEach((j, k) => {
          j.data = j.data ? j.data : []
          for (let i = j.data.length - 1; i >= 0; i--) {
            j.data[i].fieldName = j.tabname_ + '#' + j.data[i].fieldName

            if (j.data[i].fieldName in this.EditMap) {
              j.data[i].id = j.data[i].fieldName
              j.data[i].check = false
              j.data[i].label = this.EditMap[j.data[i].fieldName].label
              j.data[i].hidden = this.EditMap[j.data[i].fieldName].options.hidden
            } else {
              res.data[k].data.splice(i, 1)
            }
          }
          this.udata = this.udata.concat(j.data)
          // 转中文
          switch (j.type_) {
            case 90400: {
              j.type_ = this.Tp_tab[j.type_].name
              j.color = 'blue'
              break
            }
            case 90401: {
              j.type_ = this.Tp_tab[j.type_].name
              j.color = 'green'
              break
            }
            case 90402: {
              j.type_ = this.Tp_tab[j.type_].name
              j.color = 'cyan'
              break
            }
            case 90403: {
              j.type_ = this.Tp_tab[j.type_].name
              j.color = 'orange'
              break
            }
            default: {
              break
            }
          }
        })
        // 上面下标会变, 在循环一次下标就确定了
        res.data.forEach((j, k) => {
          for (let i = j.data.length - 1; i >= 0; i--) {
            this.fieldMap[j.data[i].fieldName] = { key: k, index: i }
          }
        })
      }
      this.fieldList = res.data || []
      this.fieldLoading = false

      // console.log('***', this.fieldList, this.fieldMap)
    },
    // 获取子组件渲染数据
    async sGetEditData(editMap) {
      this.EditMap = editMap
      this.loading = false
      // console.log('编辑数据', editMap)
      // 这里有异步问题, 表单数据要先获取
      let res = await this.FindFieldList()
      // console.log('字段列表', res)
      this.findInit(res)
      // 回显已保存的编辑字段
      this.getSetpFieldList()
    },
    // 查询表字段
    async FindFieldList() {
      let res = await findTableFieldList(this.$route.params.formid)
      return res
    },
    // 子组件双击保存
    sAddItem(type, value) {
      // json配置了表里不存在的字段
      console.log('双击保存', type, value, value.type, this.fieldMap)
      // ^ 文本控件没有pkid, 用key来配置
      let item = {}
      if (value.type == 'text') {
        console.log('text', value)
        // 可以不显示
        item.fieldName = value.key
        item.hidden = 90601
        item.label = value.label
        // return
      } else {
        // console.log('+++++++++', value.pk, this.fieldMap)
        if (!(value.pk in this.fieldMap)) {
          this.$message.error('表数据没有对应的字段')
          return
        }
        this.fieldList[this.fieldMap[value.pk].key].data[this.fieldMap[value.pk].index].check = true
        item = this.fieldList[this.fieldMap[value.pk].key].data[this.fieldMap[value.pk].index]
      }
      // console.log('保存', item, item.hidden ? 90601 : 90600)
      if (this.alreadyList.includes(item.fieldName) && type) {
        this.$message.warning('已经选择了这个字段')
        return
      }

      let stepfield = {
        formid_: this.$route.params.formid, // 表单定义id
        stepid_: this.$route.params.stepid, // 流程当前环境id
        field_: item.fieldName, // 选中字段名称
        status_: item.hidden ? 90601 : 90600, // 状态默认可编辑, 隐藏字段默认隐藏
        value_: '', // 默认值
        variname_: '', // 管理流程变量名称
        label_: item.label,
        hidden: item.hidden,
      }
      this.alreadyList.push(value.type == 'text' ? value.key : value.pk)
      this.configureList.push(stepfield)
    },
    // 子组件给当前选中的id
    sSetActive(active, value) {
      // console.log('激活id', active, value.pk)
      if (active) {
        if (this.alreadyList.includes(value.pk)) {
          this.$refs[`select${value.pk}`][0].style.backgroundColor = '#e6f7ff'
        }
      } else {
        if (this.alreadyList.includes(value.pk)) {
          this.$refs[`select${value.pk}`][0].style.backgroundColor = '#fff'
        }
      }
    },
    // 回显已保存的编辑字段
    getSetpFieldList() {
      this.queryParam.f_formid_ = this.$route.params.formid
      this.queryParam.f_stepid_ = this.$route.params.stepid
      setpFieldList(this.queryParam).then((res) => {
        console.log('回显字段', res, this.fieldMap)
        if (res.code == 0) {
          this.configureList = res.data.records || []
          // 字段列表同步勾选设置过的数据
          this.configureList.forEach((v) => {
            this.alreadyList.push(v.field_)
            if (v.field_ in this.fieldMap) {
              this.fieldList[this.fieldMap[v.field_].key].data[this.fieldMap[v.field_].index].check = true
            }
          })
          this.spinning = false
        }
      })
    },
    // 弹出层保存
    modelSave() {
      //- 数据格式化
      this.fieldList.forEach((v) => {
        v.data.forEach((j) => {
          // console.log('*', j, this.selectedRowKeys)
          if (this.selectedRowKeys.includes(j.fieldName)) {
            j.check = true
          } else {
            j.check = false
          }
        })
      })

      // 处理逻辑
      let checkMap = {}
      this.fieldList.forEach((j, k) => {
        j.data.forEach((v, i) => {
          if (v.check) {
            checkMap[v.fieldName] = v
          }
        })
      })
      // console.log('有几个', checkMap, this.alreadyList)
      // 如果已选择的字段弹出层取消掉了, 则减回去
      for (let i = this.alreadyList.length - 1; i >= 0; i--) {
        console.log('不包含', this.alreadyList[i], !(this.alreadyList[i] in checkMap))
        if (!(this.alreadyList[i] in checkMap)) {
          delete checkMap[this.alreadyList[i]]
          this.alreadyList.splice(i, 1)
          this.configureList.splice(i, 1)
        }
      }
      // 如果已选择的字段没有弹出层勾选的项, 则加回去
      for (let key in checkMap) {
        console.log('key', this.alreadyList.includes(key) == false, this.alreadyList)
        if (this.alreadyList.includes(key) == false) {
          let stepfield = {
            formid_: this.$route.params.formid, // 表单定义id
            stepid_: this.$route.params.stepid, // 流程当前环境id
            field_: checkMap[key].fieldName, // 选中字段名称
            status_: checkMap[key].hidden ? 90601 : 90600, // 状态默认可编辑, 隐藏字段默认隐藏
            value_: '', // 默认值
            variname_: '', // 管理流程变量名称
            label_: checkMap[key].label,
            hidden: checkMap[key].hidden,
          }
          this.alreadyList.push(checkMap[key].fieldName)
          this.configureList.push(stepfield)
        }
      }

      this.modelShow(false)
    },
    // 弹出层取消
    modelShow(show) {
      // 回显配置
      this.selectedRowKeys = []
      // console.log('已配置', this.configureList)
      this.configureList.forEach((v) => {
        this.selectedRowKeys.push(v.field_)
      })
      this.isModel = show
    },
    // 弹出层选中字段
    modalClick(index, item) {
      // 选中了打钩
      this.fieldList[this.fieldMap[item.fieldName].key].data[this.fieldMap[item.fieldName].index].check =
        !this.fieldList[this.fieldMap[item.fieldName].key].data[this.fieldMap[item.fieldName].index].check
    },

    // 控件失去焦点
    colBlur(index, item) {
      this.$refs.formView.fSetActive('')
      this.$refs[`select${item.field_}`][0].style.backgroundColor = '#fff'
    },
    // 控件获得焦点
    colForcus(index, item) {
      this.$refs.formView.fSetActive(item.field_)
      this.$refs[`select${item.field_}`][0].style.backgroundColor = '#e6f7ff'
    },
    // 删除选中的项
    delCol(index, item) {
      this.configureList.splice(index, 1)
      this.alreadyList.splice(this.alreadyList.indexOf(item.field_), 1)
    },

    // 保存按钮
    handleSave(status) {
      if (this.key == '1') {
        this.loading = true
        console.log('字段配置', status)
        this.setpFieldBatchSave(status)
      } else {
        console.log('按钮配置', status)
        this.$refs.btnRef.stepbtnSave(status)
      }
    },
    setpFieldBatchSave(status) {
      // 加上索引
      this.configureList.forEach((v, i) => {
        v.indexsort = i
      })
      console.log('保存', this.configureList)
      setpFieldBatchSave(this.$route.params.formid, this.$route.params.stepid, this.configureList)
        .then((res) => {
          if (res.code == 0) {
            this.$message.success('保存成功')
            if (status) {
              setTimeout(() => {
                this.handleBack()
              }, 1000)
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 返回
    handleBack() {
      this.$router.push({
        path: `/Wf_NodeGuide/${this.$route.params.operation}/${this.$route.params.formid}`,
        query: { pageIndex: this.$route.query.pageIndex },
      })
    },
  },
  components: {
    TaskFormView,
    NodeBtn,
  },
}
</script>

<style lang="less" scoped>
.modelBox {
  height: 450px;
  overflow: auto;
}
/deep/ .ant-input,
/deep/ .ant-select-selection__rendered,
/deep/ .ant-input-number-input-wrap,
/deep/ .ant-time-picker-input {
  background-color: #fff !important;
}
// /deep/ .
.tipTextBox {
  text-align: center;
  color: rgb(172, 167, 167);
}
.tipBox {
  width: 100%;
  height: 10%;
  display: flex;
  justify-content: center;
}
.imgBox {
  width: 45%;
  height: 45%;
  margin-top: 10%;
}
.rowTitleBox {
  text-align: center;
  width: 100%;
  font-size: 22px;
  font-weight: 600;
  margin: 18px 0;
  color: rgb(102, 142, 250);
}
.closeBox {
  color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 2px;
}
.modalBox {
  width: 50%;
  width: 600px;
}
/deep/ .ant-card-body {
  padding: 10px !important;
}
.cardBox {
  height: 50px;
  width: 100%;
  background-color: white;
  box-shadow: 0 2px 4px 0 #ccc;
  border-radius: 5px;
  display: inline-block;
  vertical-align: top;
  margin-top: 4px;
  display: flex;
  align-items: center;
}
.rowBox,
.titleRowCardBox {
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.titleRowBox {
  display: flex;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #ccc;
  padding-left: 2.5%;
}
.gundongBox {
  height: 65vh;
  overflow: auto;
  position: relative;
  // border: 1px solid blue;
}
.fieldDescriptionBox {
  color: rgb(138, 196, 223);
}
.nameBox {
  font-weight: 600;
}
.rowBox {
  border-bottom: 1px solid #ccc;
  padding: 0 5%;
  // background-color: red;
  z-index: 999;
}
.tableBox {
  height: 90%;
  // border: 1px solid blue;
}
.leftBox,
.rightBox {
  height: 72vh;
  width: 49%;
  float: left;
  zoom: 1;
}
.leftBox {
  border: 1px solid #e8e8e8;
  margin-right: 2%;
}
.buttonBox {
  clear: both;
  text-align: center;
  padding-top: 20px;
}
</style>